package com.lw.extraceim.ui.activity.tp;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.TextView;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.Polyline;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.model.LatLng;
import com.google.gson.reflect.TypeToken;
import com.lw.extraceim.R;
import com.lw.extraceim.loader.PackageLoader;
import com.lw.extraceim.loader.RouteLoader;
import com.lw.extraceim.model.PackageRoute;
import com.lw.extraceim.model.TransPackage;
import com.lw.extraceim.net.HttpResponseParam;
import com.lw.extraceim.net.ResponseCode;
import com.lw.extraceim.net.callback.HttpResponseParamCallback;
import com.lw.extraceim.ui.activity.base.BaseActivity;
import com.lw.extraceim.util.JsonUtils;
import com.lw.extraceim.util.MapUtils;

import org.json.JSONException;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Call;

/**
 * @Author : liwei
 * @Email : 1759840027@qq.com
 * @Description : 包裹的详细信息界面包裹包裹的物流信息
 * @Date : 2019/4/24 21:32
 */
public class PackageInfoActivity extends BaseActivity {
    private static final String TAG = "PackageInfoActivity";
    private ImageButton btnBack;
    private TextView mTvSave;

    private EditText mEdPackageNo;
    private EditText mEdPackageStatus;
    private EditText mEdPackageFrom;
    private EditText mEdPackageTo;

    private MapView mMapView;
    private TextView mTvNoData;

    private TransPackage transPackage;//当前界面的TransPackage信息

    private RouteLoader loader;

    private List<PackageRoute> routeList;


    BitmapDescriptor startBD = BitmapDescriptorFactory
            .fromResource(R.drawable.ic_me_history_startpoint);
    BitmapDescriptor finishBD = BitmapDescriptorFactory
            .fromResource(R.drawable.ic_me_history_finishpoint);


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void initView() {
        setContentView(R.layout.acitvity_package_info);
        btnBack = findViewById(R.id.btn_back);
        mTvSave = findViewById(R.id.tv_save);

        mEdPackageNo = findViewById(R.id.ed_package_no);
        mEdPackageStatus = findViewById(R.id.ed_package_status);
        mEdPackageFrom = findViewById(R.id.ed_package_from);
        mEdPackageTo = findViewById(R.id.ed_package_to);

        mMapView = findViewById(R.id.mapView);
        mTvNoData = findViewById(R.id.tv_no_data);

    }

    @Override
    public void initData() {
        loader = new RouteLoader(this);
        routeList = new ArrayList<>();
        transPackage = (TransPackage) getIntent().getSerializableExtra("transPackage");
        Log.d(TAG, "initData: " + transPackage);
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                Log.d(TAG, "run: " + System.currentTimeMillis());
                if (transPackage != null) {
                    loadRoute(transPackage.getId());
                }
            }
        }, 0, 60000);
    }

    @Override
    public void refreshUI() {
        if (transPackage != null) {
            mEdPackageNo.setText(transPackage.getId());
            mEdPackageStatus.setText(transPackage.getStatusString());
            mEdPackageFrom.setText(transPackage.getSourceNode());
            mEdPackageTo.setText(transPackage.getTargetNode());
            mMapView.setVisibility(FrameLayout.VISIBLE);
            mTvNoData.setVisibility(FrameLayout.GONE);
        } else {
            mMapView.setVisibility(FrameLayout.GONE);
            mTvNoData.setVisibility(FrameLayout.VISIBLE);
        }

    }

    //更新map地图
    public void refreshMapMapView() {
        if (routeList != null && !routeList.isEmpty() && routeList.size() > 2) {
            Marker mMarkerA;
            Marker mMarkerB;
            InfoWindow mInfoWindow;
            //更新mapView中的信息
            BaiduMap mBaiduMap = mMapView.getMap();
            // 开启定位图层
            mBaiduMap.setMyLocationEnabled(true);
            Polyline mPolyline;
            Log.d(TAG, "refreshMapMapView: " + routeList);
            mBaiduMap.clear();//清空map的所有信息
            List<LatLng> latLngs = MapUtils.coordinateConvert(routeList);//将routeList的点转换为百度坐标点
            MapStatus.Builder builder = new MapStatus.Builder();
            builder.target(latLngs.get(0)).zoom(18f);
            mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
            MarkerOptions oStart = new MarkerOptions();//地图标记覆盖物参数配置类
            oStart.position(latLngs.get(0));//覆盖物位置点，起点
            Log.d(TAG, "refreshMapMapView: " + latLngs.get(0));
            Log.d(TAG, "refreshMapMapView: " + latLngs.get(latLngs.size() - 1));
            oStart.icon(startBD);//设置覆盖物图片
            // oStart.zIndex(1);//设置覆盖物Index
            mMarkerA = (Marker) (mBaiduMap.addOverlay(oStart)); //在地图上添加此图层
            //添加终点图层
            MarkerOptions oFinish = new MarkerOptions().position(latLngs.get(latLngs.size() - 1)).icon(finishBD);
            mMarkerB = (Marker) (mBaiduMap.addOverlay(oFinish));

            OverlayOptions ooPolyline = new PolylineOptions().width(13).color(0xAAFF0000).points(latLngs);

            mPolyline = (Polyline) mBaiduMap.addOverlay(ooPolyline);
        }
    }

    public void loadRoute(String packageId) {
        loader.getPackageRoute(packageId, new HttpResponseParamCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                alert("网络错误" + e.getMessage());
            }

            @Override
            public void onResponse(HttpResponseParam response, int id) {
                Log.d(TAG, "onResponse: " + response.reseponseJson);
                if (response.code.getCode() == ResponseCode.SUCESS) {
                    try {
                        routeList = JsonUtils.fromJson(response.reseponseJson.getJSONArray("routeList").toString(), new TypeToken<List<PackageRoute>>() {
                        });
                        refreshMapMapView();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    alert("获取位置信息失败");
                }
            }
        });
    }

    @Override
    public void initEvent() {
        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    public void onBackPressed() {
        finish();
    }


    /**
     * 启动PackageInfoActivity
     *
     * @param context
     * @param transPackage
     */
    public static void actionStart(Context context, TransPackage transPackage) {
        Intent intent = new Intent(context, PackageInfoActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("transPackage", transPackage);
        intent.putExtras(bundle);
        context.startActivity(intent);
    }

}
